package com.android.publicModule.system;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.publicModule.network.EncodeUploadData;
import com.android.publicModule.tools.DeviceIDFactory;
import com.android.publicModule.tools.Tools;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.DisplayMetrics;
import android.view.WindowManager;

/**
 * 手机基本信息读取及当前应用相关信息获取类
 * @author 张少志
 *
 */
public class SystemInfo {

	//WIFI
	public static final String NETWORK_TYPE_WIFI = "WIFI";
	//移动
    public static final String NETWORK_TYPE_CMWAP = "cmwap";
    public static final String NETWORK_TYPE_CMNET = "cmnet";
    //联通
    public static final String NETWORK_TYPE_3GWAP = "3gwap";
    public static final String NETWORK_TYPE_3GNET = "3gnet";
    public static final String NETWORK_TYPE_UNIWAP = "uniwap";
    public static final String NETWORK_TYPE_UNINET = "uninet";
    //电信
    public static final String NETWORK_TYPE_CTWAP = "ctwap";
    public static final String NETWORK_TYPE_CTNET = "ctnet";
    //其他扩展类型
    public static final String NETWORK_TYPE_MOBILE_DUN = "dun";
    public static final String NETWORK_TYPE_MOBILE_HIPRI = "hipri";
    public static final String NETWORK_TYPE_MOBILE_MMS = "mms";
    public static final String NETWORK_TYPE_MOBILE_SUPL = "supl";
    public static final String NETWORK_TYPE_WIMAX = "wimax";
    //无网络
    public static final String NETWORK_TYPE_NONE = "unknow";
    //SIM卡类型
    public static final String CHINA_MOBILE = "mobile";//"移动";
    public static final String CHINA_UNICOM = "unicom";//"联通";
    public static final String CHINA_TELECOM = "telecom";//"电信";
    public static final String UNKNOW_TYPE = "unknow";//"未知";
  //当前正在使用的APN
    private static Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn");
    private static Uri PREFERRED_APN_URI2 = Uri.parse("content://telephony/carriers/preferapn2");
    
    public static boolean ENCRYPT_UPLOAD_DATA = true;//是否加密上传数据
    public static boolean DECRYPT_DOWNLOAD_DATA = true;//是否解密下载数据
    public static boolean NEED_INSTALL_ASSET_VPS = true;//是否需要安装VPS
    public static boolean USE_SPEAK_CACHE_ENABLE = true;//是否使用缓存
    public static boolean USE_SPEAK_CACHE_FIRST = true;//是否优先使用缓存
    
    public static final String GOOGLE_VOICE_SEACH_APK ="com.google.android.voicesearch.apk";//谷歌语音安装包
    
    public static final int LAUNCH_WIDGET = 1 ;//入口为Widget
	public static final int LAUNCH_YY = 2 ;//入口为YY
	
	public static final String ANDROID = "android";//framwork应用包名
	public static final String SETTINGS = "com.android.settings";//系统设置应用包名
	
    /**
     * 获取代理
     */
    public static Proxy getProxy(Context context) {
    	Proxy proxy = null;
        try {
            if (!getNetworkInfo(context).equals(NETWORK_TYPE_WIFI))
            {
	            String proxyHost = android.net.Proxy.getDefaultHost();
	            int proxyPort = android.net.Proxy.getDefaultPort();
	            if (proxyHost != null && proxyHost.length()>0 && proxyPort!=-1)
	            {
	            	proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
	            }
            }
        } catch (Exception e) {
        }
        return proxy;
    }
    
    /**
     * 检测当前网络是否可用
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
    	boolean available = false;
    	ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if (network != null && network.isAvailable() && network.isConnected())//当前网络可用并且已经连接
        {
        	available = true;
        }
        return available;
    }
    
    /**
     * 判断当前是否为wap网络
     * @param context
     * @return
     */
    public static boolean isCurrentWapNetwork(Context context) {
    	boolean iswap = false;
    	String networkInfo = getNetworkInfo(context);
    	if(networkInfo.equals(NETWORK_TYPE_CMWAP)||networkInfo.equals(NETWORK_TYPE_3GWAP)||networkInfo.equals(NETWORK_TYPE_UNIWAP)||networkInfo.equals(NETWORK_TYPE_CTWAP))
    	{
    		iswap = true;
    	}
    	return iswap;
    }
    
    /**
     * 获取当前正在使用的APN
     * @param context
     * @return
     */
    public static String getCurrentAPN(Context context) {
    	String apn = null;
    	try {
	    	Cursor cursor = context.getContentResolver().query(PREFERRED_APN_URI, null, null, null,null);
	        if (cursor != null && cursor.moveToFirst())
	        {
	            apn = cursor.getString(cursor.getColumnIndex("apn"));
	            cursor.close();
	            cursor = null;
	        }
	        else
	        {
	        	cursor = context.getContentResolver().query(PREFERRED_APN_URI2, null, null, null,null);
	        	if (cursor != null && cursor.moveToFirst())
	            {
	                apn = cursor.getString(cursor.getColumnIndex("apn"));
	                cursor.close();
	                cursor = null;
	            }
	        }
    	} catch(Exception e) {
    		
    	}
        return apn;
    }
    
    /**
     * 获取当前网络类型
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
    	int networkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
    	TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    	networkType = tm.getNetworkType();
    	return networkType;
    }
    
    /**
     * 获取当前网络类型
     * @param context
     * @return
     */
    public static String getNetworkInfo(Context context) {
        ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        String mNetworkInfo = NETWORK_TYPE_NONE;
        if (network != null&&network.isAvailable())// && network.isConnected() //&& network.isAvailable() 
        {
        	int type = network.getType();
            switch (type)
            {
            	case ConnectivityManager.TYPE_WIFI:
            		mNetworkInfo = NETWORK_TYPE_WIFI;
            		break;
                
                case ConnectivityManager.TYPE_MOBILE:
                case 15://兼容马维尔平台方案
                	String apnName = getCurrentAPN(context);
                	if(apnName!=null)
                	{
                		mNetworkInfo = apnName.toLowerCase();
                	}
                	break;
                    
                case ConnectivityManager.TYPE_MOBILE_DUN:
                	mNetworkInfo = NETWORK_TYPE_MOBILE_DUN;
            		break;
            		
                case ConnectivityManager.TYPE_MOBILE_HIPRI:
                	mNetworkInfo = NETWORK_TYPE_MOBILE_HIPRI;
            		break;
            		
                case ConnectivityManager.TYPE_MOBILE_MMS:
                	mNetworkInfo = NETWORK_TYPE_MOBILE_MMS;
            		break;
            		
                case ConnectivityManager.TYPE_MOBILE_SUPL:
                	mNetworkInfo = NETWORK_TYPE_MOBILE_SUPL;
            		break;
            		
                case ConnectivityManager.TYPE_WIMAX:
                	mNetworkInfo = NETWORK_TYPE_WIMAX;
            		break;
                    
                default:
                    mNetworkInfo = NETWORK_TYPE_NONE;
                    break;
            }
        }
        return mNetworkInfo;
    }
    
    /**
     * 获取手机唯一编号
     */
    private static String imei;//手机设备唯一编号
    public static String getIMEI(Context context) {
    	if(imei==null&&context!=null)
    	{
	        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
	        imei = tm.getDeviceId();// 手机串号
	        if(imei==null||imei.length()==0)
	    	{
	        	imei = "000000000000000";
	    	}
    	}
        return imei;
    }
    
    /**
     * 获取SIM卡唯一编号
     */
    private static String imsi;//SIM卡唯一编号
    public static String getIMSI(Context context) {
    	if(imsi==null&&context!=null)
    	{
	    	TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
	        imsi = tm.getSubscriberId();
	        if(imsi==null||imsi.length()==0)
	    	{
	        	imsi = "000000000000000";
	    	}
    	}
        return imsi;
    }
    
    /**
     * 获取手机型号
     */
    private static String model;//手机型号
    public static String getModel() {
    	if(model==null)
    	{
    		model = android.os.Build.MODEL;
    	}
    	return model;
    }
	
    /**
     * 获取Android系统版本
     */
    private static String androidRelease;//Android系统版本
    public static String getAndroidRelease() {
    	if(androidRelease==null)
    	{
    		androidRelease = android.os.Build.VERSION.RELEASE;
    	}
    	return androidRelease;
    }
    
    /**
     * 获取Android系统API版本号
     */
    private static int androidSDKINT;//Android系统API版本号
    public static int getAndroidSDKINT() {
    	if(androidSDKINT==0)
    	{
    		androidSDKINT = android.os.Build.VERSION.SDK_INT;
    	}
    	return androidSDKINT;
    }
    
    /**
     * 获取手机号码
     */
    private static String phoneNumber;//手机号码
    public static String getPhoneNumber(Context context) {
    	if(phoneNumber==null)
    	{
    		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    		phoneNumber = tm.getLine1Number();
    	}
        return phoneNumber;
    }
    
    /**
     * 获取运营商
     */
    private static String cardType;//运营商
    public static String getCardType(Context context) {
    	if(cardType==null)
    	{
            String imsi = getIMSI(context);
            cardType = UNKNOW_TYPE;
            if (imsi != null) 
            {
                if (imsi.startsWith("46000") || imsi.startsWith("46002") || imsi.startsWith("46007")) 
                {
                    cardType = CHINA_MOBILE;// 中国移动
                }
                else if (imsi.startsWith("46001")) 
                {
                    cardType = CHINA_UNICOM;// 中国联通
                }
                else if (imsi.startsWith("46003")) 
                {
                    cardType = CHINA_TELECOM;// 中国电信
                }
            }
    	}
        return cardType;
    }
    
    /**
     * 获取MAC地址
     */
    private static String mac;//MAC地址
    public static String getMAC(Context context) {
    	if(mac==null)
    	{
	        WifiManager wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
	        WifiInfo info = wifi.getConnectionInfo();
	        if(info!=null)
	        {
	        	mac = info.getMacAddress();
	        }
    	}
        return mac;
    }
    
    /**
     * 获取屏幕宽度
     */
    private static int mScreenWidthPixels;// 宽
    public static int getScreenWidth(Context context) {
    	if(mScreenWidthPixels<=0)
    	{
    		setScreenInfomation(context);
    	}
        return mScreenWidthPixels;
    }
    
    /**
     * 获取屏幕高度
     */
    private static int mScreenHeightPixels;// 高
    public static int getScreenHeight(Context context) {
    	if(mScreenHeightPixels<=0)
    	{
    		setScreenInfomation(context);
    	}
        return mScreenHeightPixels;
    }
    
    /**
     * 获取屏幕分辨率
     */
    private static String screen;//屏幕分辨率
    public static String getScreen(Context context) {
    	if(screen==null)
    	{
    		screen = getScreenWidth(context) + "x" + getScreenHeight(context);
    	}
        return screen;
    }
    
    /**
     * 获取屏幕尺寸
     */
    private static String screenSize;//屏幕分辨率
    public static String getScreenSize(Context context) {
    	if(screenSize==null)
    	{
    		screenSize = String.format("%.1f",Math.sqrt((Math.pow(getScreenWidth(context),2) + Math.pow(getScreenHeight(context),2)))/getDensityDpi(context));
    	}
        return screenSize;
    }
    
    /**
     * 获取屏幕密度
     */
    private static float density;// 屏幕密度
    public static float getDensity(Context context) {
    	if(density<=0f)
    	{
    		setScreenInfomation(context);
    	}
        return density;
    }
    
    /**
     * 获取屏幕密度系数
     */
    private static int densityDpi;// 屏幕密度系数
    public static int getDensityDpi(Context context) {
    	if(densityDpi<=0)
    	{
    		setScreenInfomation(context);
    	}
        return densityDpi;
    }

    /**
     * 设置当前屏幕分辨率
     */
    public static void setScreenInfomation(Context context) {
    	DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        mScreenWidthPixels = dm.widthPixels;
        mScreenHeightPixels = dm.heightPixels;
        if(mScreenHeightPixels>0&&mScreenHeightPixels>0)
        {
        	screen = mScreenWidthPixels + "x" + mScreenHeightPixels;
        }
        density = dm.density;
        densityDpi = dm.densityDpi;
    }
    
    /**
     * 获取当前SIM卡的状态
     * @param context
     * @return
     */
    public static int getSimState(Context context) {
    	int simState = TelephonyManager.SIM_STATE_UNKNOWN;
    	try {
            TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            simState = tm.getSimState();// sim卡当前状态
        } catch (Exception e) {
        }
        return simState;
    }
    
    /**
	  * 获取手机CellId
	  * @param context
	  * @return
	  */
    private static int cellId;
    public static int getCellId(Context context) {
    	if(cellId==0)
    	{
    		cellId = -1;
	    	if(context!=null)
		    {
		    	int ACCESS_FINE_LOCATION_PERMISSION = context.checkCallingOrSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
		    	int ACCESS_COARSE_LOCATION_PERMISSION = context.checkCallingOrSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
		    	if(ACCESS_FINE_LOCATION_PERMISSION == PackageManager.PERMISSION_GRANTED || ACCESS_COARSE_LOCATION_PERMISSION == PackageManager.PERMISSION_GRANTED)
		    	{
			    	TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			    	CellLocation  cellLocation = tm.getCellLocation();
			    	if(cellLocation!=null)
			    	{
			    		if(cellLocation instanceof GsmCellLocation)
			    		{
			    			GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
			    			cellId = gsmCellLocation.getCid();
			    			lac = gsmCellLocation.getLac();
			    		}
			    		else if(cellLocation instanceof CdmaCellLocation)
			    		{
			    			CdmaCellLocation cdma = (CdmaCellLocation) cellLocation;
			    			cellId = cdma.getBaseStationId();
			    			lac = cdma.getNetworkId();
			    		}
			    	}
		    	}
	    	}
    	}
    	return cellId;
    }
    
    /**
	  * 获取手机Lac
	  * @param context
	  * @return
	  */
    private static int lac;
    public static int getLac(Context context) {
    	if(lac==0)
    	{
    		lac = -1;
	    	if(context!=null)
		    {
		    	int ACCESS_FINE_LOCATION_PERMISSION = context.checkCallingOrSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
		    	int ACCESS_COARSE_LOCATION_PERMISSION = context.checkCallingOrSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
		    	if(ACCESS_FINE_LOCATION_PERMISSION == PackageManager.PERMISSION_GRANTED || ACCESS_COARSE_LOCATION_PERMISSION == PackageManager.PERMISSION_GRANTED)
		    	{
			    	TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			    	CellLocation  cellLocation = tm.getCellLocation();
			    	if(cellLocation!=null)
			    	{
			    		if(cellLocation instanceof GsmCellLocation)
			    		{
			    			GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
			    			lac = gsmCellLocation.getLac();
			    			cellId = gsmCellLocation.getCid();
			    		}
			    		else if(cellLocation instanceof CdmaCellLocation)
			    		{
			    			CdmaCellLocation cdma = (CdmaCellLocation) cellLocation;
			    			lac = cdma.getNetworkId();
			    			cellId = cdma.getBaseStationId();
			    		}
			    	}
		    	}
	    	}
   		}
   		return lac;
    }
    
    /**
     * 获取当前应用包名
     */
    private static String packageName;
    public static String getPackageName(Context context) {
    	if(packageName==null&&context!=null)
    	{
    		packageName = context.getPackageName();
    	}
    	return packageName;
    }
    
    /**
     * 获取当前应用版本名称
     */
    private static String versionName;
    public static String getVersionName(Context context) {
    	if(versionName==null)
    	{
	    	PackageInfo info = Tools.getPackageInfo(context, getPackageName(context),PackageManager.GET_UNINSTALLED_PACKAGES);
	    	if(info!=null)
	    	{
	    		versionName = info.versionName;
	    		versionCode = info.versionCode;
	    	}
    	}
    	return versionName;
    }
    
    /**
     * 获取当前应用版本号
     */
    private static int versionCode;
    public static int getVersionCode(Context context) {
    	if(versionCode==0)
    	{
	    	PackageInfo info = Tools.getPackageInfo(context, getPackageName(context),PackageManager.GET_UNINSTALLED_PACKAGES);
	    	if(info!=null)
	    	{
	    		versionCode = info.versionCode;
	    		versionName = info.versionName;
	    	}
    	}
    	return versionCode;
    }
    
    private static int access = LAUNCH_YY;//默认
    public static int getAccess() {
    	return access;
    }
    
    public static void setAccess(int a) {
    	access = a;
    }
    
    private static String currentAppSignature;
    public static String getCurrentAppSignature(Context context) {
    	if(currentAppSignature==null||currentAppSignature.length()==0)
    	{
    		String packageSignature = Tools.getPackageSignature(Tools.getPackageInfo(context, getPackageName(context),PackageManager.GET_SIGNATURES));
    		currentAppSignature = Tools.getUniqueString(packageSignature);
    		Tools.showLog("mugekey", "currentAppSignature="+currentAppSignature);
    		Tools.showLog("mugekey", "packageSignature="+packageSignature);
    	}
    	return currentAppSignature;
    }
    
    public static String getPhoneInfo(Context context) {
    	PlatformManager mPlatformManager = PlatformManager.getInstance(context);
    	String phoneInfo = "手机平台："+mPlatformManager.getCurrentPlatform(context);
    	phoneInfo += "\nIMEI："+getIMEI(context);
    	phoneInfo += "\nIMSI："+getIMSI(context);
    	phoneInfo += "\n手机型号："+getModel();
    	String cardType = getCardType(context);
    	if(cardType.equals(CHINA_MOBILE))
    	{
    		cardType = "移动";
    	}
    	else if(cardType.equals(CHINA_UNICOM))
    	{
    		cardType = "联通";
    	}
    	else if(cardType.equals(CHINA_TELECOM))
    	{
    		cardType = "电信";
    	}
    	else
    	{
    		cardType = "未知";
    	}
    	phoneInfo += "\n运营商："+cardType;
    	phoneInfo += "\nAndroid系统版本："+getAndroidRelease();
    	phoneInfo += "\n手机分辨率："+getScreen(context);
    	phoneInfo += "\n屏幕尺寸："+getScreenSize(context);
    	String installInfo = "未安装";
    	int installType = getInstallType(context, getPackageName(context));
    	if(installType==INSTALL_TYPE_SYSTEM)
    	{
    		installInfo = "系统区";
    	}
    	else if(installType==INSTALL_TYPE_DATA)
    	{
    		installInfo = "用户区";
    	}
    	else if(installType==INSTALL_TYPE_SDCARD)
    	{
    		installInfo = "SD卡";
    	}
    	phoneInfo += "\nYY安装位置："+installInfo;
    	phoneInfo += "\nYY渠道号："+getChannelId(context);
    	phoneInfo += "\nYY版本号："+getVersionName(context);
    	String ciInfo = "未安装";
    	String ci = getInstallChannelInfo(context);
    	if(ci.equals("1"))
    	{
    		ciInfo = "安装在系统区";
    	}
    	else if(ci.equals("0"))
    	{
    		ciInfo = "安装在用户区";
    	}
    	phoneInfo += "\n渠道包安装信息："+ciInfo;
    	return phoneInfo;
    }
    
    public static void setTestChannelId(Context context,String id) {
    	channelId = id;
    	Tools.saveData(context, packageName, "channelId", channelId);
    }
    
    /**
     * 获取渠道号
     * @param context
     * @return
     */
    private static final String DEFAULT_EXCEPTION_CHANNEL_ID = "9999";//数据读取异常时的默认渠道号
    private static String channelId;
    public static String getChannelId(Context context) {
    	if(channelId==null)
    	{
    		String packageName = getPackageName(context);
    		channelId=Tools.getSaveData(context, packageName, "channelId", null);
    		if(channelId==null)
    		{
	    		ApplicationInfo appInfo;
				try {
					appInfo = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
					if (appInfo!=null)
		    		{
		    			Bundle metaData = appInfo.metaData;
		    			if(metaData!=null)
		    			{
		    				if(metaData.containsKey("channelId"))
		    				{
		    					channelId = metaData.getString("channelId");
		    				}
		    			}
			      	}
				} catch (NameNotFoundException e) {
				} catch (Exception e) {
				}
				if(channelId!=null)
				{
					Tools.saveData(context, packageName, "channelId", channelId);
				}
    		}
    	}
    	return channelId;
    }
    
    /**
     * 获取标准GET参数
     * @param context
     * @return
     */
    @SuppressWarnings("deprecation")
	public static String requestUploadGetParam(Context context) {
    	String getParam = "";
    	getParam+="channelId="+URLEncoder.encode(getChannelId(context));
    	getParam+="&imei="+URLEncoder.encode(getIMEI(context));
    	getParam+="&imsi="+URLEncoder.encode(getIMSI(context));
    	getParam+="&check="+URLEncoder.encode(MD5(context));
    	getParam+="&model="+URLEncoder.encode(getModel());
    	getParam+="&pkgName="+URLEncoder.encode(getPackageName(context));
    	getParam+="&verName="+URLEncoder.encode(getVersionName(context));
    	getParam+="&verCode="+URLEncoder.encode(String.valueOf(getVersionCode(context)));
    	getParam+="&cellId="+URLEncoder.encode(String.valueOf(getCellId(context)));
    	getParam+="&lac="+URLEncoder.encode(String.valueOf(getLac(context)));
    	getParam+="&network="+URLEncoder.encode(getNetworkInfo(context));
    	getParam+="&release="+URLEncoder.encode(getAndroidRelease());
    	getParam+="&sdkInt="+URLEncoder.encode(String.valueOf(getAndroidSDKINT()));
    	getParam+="&cardType="+URLEncoder.encode(getCardType(context));
    	getParam+="&width="+URLEncoder.encode(String.valueOf(getScreenWidth(context)));
    	getParam+="&height="+URLEncoder.encode(String.valueOf(getScreenHeight(context)));
    	getParam+="&phoneSize="+URLEncoder.encode(Tools.getPhoneAvailableSize(context)+"/"+Tools.getPhoneTotalSize(context));
    	getParam+="&sdcardSize="+URLEncoder.encode(String.valueOf(Tools.getSDCardAvailableSize()+"/"+Tools.getSDCardTotalSize()));
    	getParam+="&internalType="+URLEncoder.encode(getAppInternal(context, context.getPackageName()));
    	getParam+="&internalPath="+URLEncoder.encode(getAppSourcePath(context, context.getPackageName()));
    	getParam+="&internalCI="+URLEncoder.encode(getInstallChannelInfo(context));
		getParam+="&mid="+URLEncoder.encode(new DeviceIDFactory(context).getMID());
    	getParam+="&access="+URLEncoder.encode(String.valueOf(getAccess()));
    	getParam+="&signature="+URLEncoder.encode(getCurrentAppSignature(context));
    	return getParam;
    }
    
    /**
     * 获取标准POST参数
     * @param context
     * @return
     */
    public static List<BasicNameValuePair> requestUploadPosttParam(Context context) {
    	List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
    	list.add(new BasicNameValuePair("channelId",getChannelId(context)));
    	list.add(new BasicNameValuePair("imei",getIMEI(context)));
    	list.add(new BasicNameValuePair("imsi",getIMSI(context)));
    	list.add(new BasicNameValuePair("check",MD5(context)));
    	list.add(new BasicNameValuePair("model",getModel()));
    	list.add(new BasicNameValuePair("pkgName",getPackageName(context)));
    	list.add(new BasicNameValuePair("verName",getVersionName(context)));
    	list.add(new BasicNameValuePair("verCode",String.valueOf(getVersionCode(context))));
    	list.add(new BasicNameValuePair("cellId",String.valueOf(getCellId(context))));
    	list.add(new BasicNameValuePair("lac",String.valueOf(getLac(context))));
    	list.add(new BasicNameValuePair("network",getNetworkInfo(context)));
    	list.add(new BasicNameValuePair("netType",String.valueOf(getNetworkType(context))));
    	list.add(new BasicNameValuePair("release",getAndroidRelease()));
    	list.add(new BasicNameValuePair("sdkInt",String.valueOf(getAndroidSDKINT())));
    	list.add(new BasicNameValuePair("cardType",getCardType(context)));
    	list.add(new BasicNameValuePair("width",String.valueOf(getScreenWidth(context))));
    	list.add(new BasicNameValuePair("height",String.valueOf(getScreenHeight(context))));
    	list.add(new BasicNameValuePair("phoneSize",Tools.getPhoneAvailableSize(context)+"/"+Tools.getPhoneTotalSize(context)));
    	list.add(new BasicNameValuePair("sdcardSize",String.valueOf(Tools.getSDCardAvailableSize()+"/"+Tools.getSDCardTotalSize())));
    	list.add(new BasicNameValuePair("internalType",getAppInternal(context, context.getPackageName())));
    	list.add(new BasicNameValuePair("internalPath",getAppSourcePath(context, context.getPackageName())));
    	list.add(new BasicNameValuePair("internalCI",getInstallChannelInfo(context)));
    	list.add(new BasicNameValuePair("mid",new DeviceIDFactory(context).getMID()));
		list.add(new BasicNameValuePair("access",getAccess()+""));
		list.add(new BasicNameValuePair("signature",getCurrentAppSignature(context)));
    	return list;
    }
    
    /**
     * 根据已知参数列表构建JSONObject
     * @param list
     * @return
     */
    public static JSONObject createJSONObject(List<BasicNameValuePair> list) {
    	JSONObject obj = null;
    	if(list!=null)
    	{
    		int len = list.size();
    		if(len>0)
    		{
    			BasicNameValuePair temp;
    			for(int i=0;i<len;i++)
    			{
    				temp = list.get(i);
    				if(temp!=null)
    				{
    					if(obj==null)
    					{
    						obj = new JSONObject();
    					}
    					try {
							obj.put(temp.getName(), temp.getValue());
						} catch (JSONException e) {
						} catch (Exception e) {
 						}
    				}
    			}
    		}
    	}
    	return obj;
    }
    
    /**
     * 返回已知参数列表构建JSONObject的字符串结构
     * @param list
     * @return
     */
    public static String createJSONObjectStr(List<BasicNameValuePair> list) {
    	JSONObject obj = createJSONObject(list);
    	if(obj!=null)
    	{
    		return obj.toString();
    	}
    	return null;
    }
    
    public static final String ENCRYPT_AND_DECRYPT_KEY = "zzwilldobetter2011";//加解密KEY
    public static final String ENCRYPT_AND_DECRYPT_CHARSET = "UTF-8";
    private static EncodeUploadData encodeUploadData;
    /**
     * 加密字符串
     * @param source
     * @return
     */
    public static String encryptData(String source) {
    	String encryptStr = null;
    	if(source!=null&&source.length()>0)
    	{
	    	if(encodeUploadData==null)
	    	{
	    		encodeUploadData = new EncodeUploadData(ENCRYPT_AND_DECRYPT_KEY);
	    	}
	    	byte[] sourceByte = null;
	    	try {
	    		sourceByte = source.getBytes(ENCRYPT_AND_DECRYPT_CHARSET);
	    	} catch(UnsupportedEncodingException e) {
	    		
	    	}
	    	if(sourceByte!=null&&sourceByte.length>0)
	    	{
	    		byte []encryptByte = encodeUploadData.EncodeAndBase64New(sourceByte);
	    		if(encryptByte!=null&&encryptByte.length>0)
	    		{
	    			try {
						encryptStr = new String(encryptByte,ENCRYPT_AND_DECRYPT_CHARSET);
					} catch (UnsupportedEncodingException e) {
					}
	    		}
	    	}
    	}
    	if(encryptStr==null)
    	{
    		encryptStr = source;
    	}
    	return encryptStr;
    }
    
    /**
     * 解密字符串
     * @param encryptStr
     * @return
     */
    public static String decryptData(String encryptStr) {
    	String source = null;
    	if(encryptStr!=null&&encryptStr.length()>0)
    	{
	    	if(encodeUploadData==null)
	    	{
	    		encodeUploadData = new EncodeUploadData(ENCRYPT_AND_DECRYPT_KEY);
	    	}
	    	byte[] encryptByte = null;
	    	try {
	    		encryptByte = encryptStr.getBytes(ENCRYPT_AND_DECRYPT_CHARSET);
	    	} catch(UnsupportedEncodingException e) {
	    		
	    	}
	    	if(encryptByte!=null&&encryptByte.length>0)
	    	{
	    		byte []sourceByte = encodeUploadData.DecodeAndBase64New(encryptByte);
	    		if(sourceByte!=null&&sourceByte.length>0)
	    		{
	    			try {
	    				source = new String(sourceByte,ENCRYPT_AND_DECRYPT_CHARSET);
					} catch (UnsupportedEncodingException e) {
					}
	    		}
	    	}
    	}
    	if(source==null)
    	{
    		source = encryptStr;
    	}
    	return source;
    }
    
    /**
     * 获取YYYY语音助理的安装状态
     */ 
    public static final String INSTALL_SYSTEM_PATH = "/system/app/";//系统区安装路径
	public static final String INSTALL_SDCARD_PATH = "/mnt/asec/";//SD卡安装路径
    public static final int INSTALL_TYPE_SDCARD = 2;
    public static final int INSTALL_TYPE_SYSTEM = 1;
    public static final int INSTALL_TYPE_DATA = 0;
    public static final int INSTALL_TYPE_NULL = -1;
    public static int getInstallType(Context context,String packageName) {
    	int installType=-2;
		ApplicationInfo info = Tools.getApplicationInfo(context, packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
		if(info!=null)
		{
			String installPath = info.sourceDir;
			if(installPath!=null)
			{
				if((installPath.startsWith(INSTALL_SYSTEM_PATH))||((info.flags&ApplicationInfo.FLAG_SYSTEM)>0)||((info.flags&ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)>0))
    			{
    				installType=INSTALL_TYPE_SYSTEM;
    			}
    			else if((installPath.startsWith(INSTALL_SDCARD_PATH))||((info.flags&ApplicationInfo.FLAG_EXTERNAL_STORAGE)>0))
    			{
    				installType=INSTALL_TYPE_SDCARD;
    			}
    			else
    			{
    				installType=INSTALL_TYPE_DATA;
    			}
			}
		}
		else
		{
			installType=INSTALL_TYPE_NULL;
		}
		Tools.showLog("muge", "getInstallType() packageName="+packageName+" installType="+installType);
    	return installType;
    }
    
    /**
     * MD5
     * @param context
     * @return
     */
    public static String MD5(Context context) {
		return MD5(getIMEI(context)+getIMSI(context)) ;
	}
    
	public static String MD5(String src) {
    	char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    	try {
			byte[] bytes = src.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(bytes);
			bytes = md.digest();
			int j = bytes.length;
			char[] chars = new char[j * 2];
			int k = 0;
			for (int i = 0; i < bytes.length; i++) {
				byte b = bytes[i];
				chars[k++] = hexChars[b >>> 4 & 0xf];
				chars[k++] = hexChars[b & 0xf];
			}
			return new String(chars);
    	}
    	catch (Exception e){
    		return null;
    	}
	}
	
	/**
     * 获取应用的安装路径（/data/data/<packageName>下或者/system/app/下）
     * @param packageName
     * @return
     */
    public  static String getAppSourcePath(Context context,String packageName) {
        if (packageName == null || packageName.length()==0)
        {
            return null;
        }
        try {
            ApplicationInfo info = context.getPackageManager()
            .getApplicationInfo(packageName,
            PackageManager.GET_UNINSTALLED_PACKAGES);
            if(info==null)
            {
            	return null;
            }
            return info.sourceDir;
        } catch (NameNotFoundException e) {
        	return null;
        }
    }
	    
    /**
     * 判断软件是否为内置安装
     * @param context
     * @param packageName
     * @return 
     */
    public static String getAppInternal(Context context,String packageName) {
    	int installType = getInstallType(context, packageName);
		if(installType==INSTALL_TYPE_SYSTEM)
		{
			return "1";
		}
		else if(installType==INSTALL_TYPE_DATA || installType==INSTALL_TYPE_SDCARD)
		{
			return "0";
		}
		else
    	{
    		return "-1";
    	}
    }
    
    /**	 
	  * 检测是否安装com.zzcm.channelinfo包
	  * @param context
	  * @return 1  为内置系统区
	  *         0  为非系统区
	  * 		-1 为没有安装
	  */
	 public static String getInstallChannelInfo(Context context)
	 {
		 int installType = getInstallType(context,"com.zzcm.channelinfo");
		 if(installType!=INSTALL_TYPE_NULL)
		 {
			 if(installType==INSTALL_TYPE_SYSTEM)
			 {
				 return "1";
			 }
			 else
			 {
				 return "0" ;
			 }
		 }
		 installType = getInstallType(context,"com.zzcm.silentinstallation");
		 if(installType!=INSTALL_TYPE_NULL)
		 {
			 if(installType==INSTALL_TYPE_SYSTEM)
			 {
				 return "1";
			 }
			 else
			 {
				 return "0" ;
			 }
		 }
		 return "-1" ;
	 }
		    
	/**
	 * 过滤以下信息
	 * com.android  (android系统)
		com.mediatek (MTK相关)
		com.google   (谷歌相关)
		com.spreadst  (展讯相关)
		com.spreadtrum (展讯相关)
	 * @param context
	 * @param isFlagSystem
	 * @return
	 */
    public static String getInstallAppPackageName(Context context,boolean isFlagSystem) {
	    String  packageName= "" ;
		List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
		//循环获取用户手机上所安装的软件信息
	    for(int i=0;i<packages.size();i++) { 
	        PackageInfo packageInfo = packages.get(i); 
	        //不是系统区应用
	        if(!isFlagSystem)
	        {
		        if((packageInfo.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)==0)
		        {
		            packageName += packageInfo.packageName;	
		            packageName += "_"+packageInfo.versionCode+"," ;
		        }
	        }//系统区应用
	        else
	        {
	        	if((packageInfo.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)>0)
		        {
	        		
	        		if(!(packageInfo.packageName.startsWith("com.android")||
	        				packageInfo.packageName.startsWith("com.mediatek")||
	        				packageInfo.packageName.startsWith("com.google")||
	        				packageInfo.packageName.startsWith("com.spreadst")||
	        				packageInfo.packageName.startsWith("com.spreadtrum")))
	        		{
	        			packageName += packageInfo.packageName;	
	        			packageName += "_"+packageInfo.versionCode+"," ;
	        		}
		        }
	        }
	    }
	    if(packageName.endsWith(","))
	    {
	    	packageName = packageName.substring(0, packageName.length()-1);
	    }
	    return packageName;
	}
	
}
